import paho.mqtt.client as mqtt

# MQTT 服务器地址和端口
MQTT_BROKER = "218.108.8.218"  # 免费的公共 MQTT 服务器
MQTT_PORT = 1883
MQTT_TOPIC = "gw/devices/coordinate"  # 订阅的主题

# 当客户端连接到 MQTT 代理时调用的回调函数
def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")
    # 订阅主题
    client.subscribe(MQTT_TOPIC)

# 当客户端从代理接收到消息时调用的回调函数
def on_message(client, userdata, msg):
    with open(outfile, "a") as file:  # 以追加模式打开文件
        print("1")
        message = f"Topic: {msg.topic}, Message: {msg.payload.decode()}\n"
        file.write(message)
    print(f"Message received and written to {outfile}: {message.strip()}")

outfile = "mqtt_messages.log"
# 创建 MQTT 客户端实例
client = mqtt.Client()

# 设置回调函数
client.on_connect = on_connect
client.on_message = on_message

# 连接到 MQTT 代理
client.connect(MQTT_BROKER, MQTT_PORT, 60)
client.username_pw_set("gwzauser", "gwza@2024")
# 启动网络循环，等待消息
try:
    client.loop_forever()
except KeyboardInterrupt:
    print("Program interrupted by user.")
except Exception as e:
    print(f"An error occurred: {e}")